package br.unifor.mia.graph.util;

import java.io.BufferedReader;
import java.io.IOException;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.unifor.mia.graph.setorcensitario.Crime;
import br.unifor.mia.graph.setorcensitario.Link;
import br.unifor.mia.graph.setorcensitario.Node;

public class ImportTextToDB {

	public static void populate(BufferedReader reader, Session session) throws IOException {
		
		Transaction trans = session.beginTransaction();

		String txtLine = null;
		do {
			txtLine = reader.readLine();

			// If the line is a comentary or it is empty, do nothing.
			if (!(txtLine != null && !(txtLine.contains("//") || txtLine.equals("")))) {
				continue;
			}

			txtLine = txtLine.replace("(", "").replace(")", "");

			String[] dataLine = txtLine.replace("[", "!").replace("]", "!").split("!");

			String sectorID = dataLine[0].replace(",","");
			
			Node sectorNode = new Node(Integer.valueOf(sectorID), "Sector" + sectorID);

			session.save(sectorNode);

			if (dataLine.length == 2) {

				String[] usersBySector = dataLine[1].split(",");

				for (String user : usersBySector) {

					String[] userData = user.split(";");
					String userID = userData[1];
					String crimeID = userData[0];

					Node userNode = (Node) session.get(Node.class, "User" + userID);
					
					if (userNode == null) {
						userNode = new Node(Integer.valueOf(userID), "User" + userID);
						session.save(userNode);
					}
					
					String linkName = "from" + userNode.getName() + "_to" + sectorNode.getName();
					Link link = (Link) session.get(Link.class, linkName);
					
					if (link == null) {
						link = new Link(linkName, userNode, sectorNode);
						session.save(link);
					}
					
					// Peso da aresta
					Crime crime = new Crime(Integer.valueOf(crimeID), link);
					session.save(crime);
					
					link.addCrime(crime);
					userNode.addUserLink(link);
					sectorNode.addSectorLink(link);
				}
			}

		} while (txtLine != null);
		
		trans.commit();
	}
}
